package com.example.demo.Service;


import com.example.demo.utils.WxPayV3Util;
import com.example.demo.utils.model.CommonResult;
import com.example.demo.utils.model.NotifyBody;
import com.example.demo.utils.model.TProduct;
import com.example.demo.utils.model.WechatPay;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;


import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.security.*;
import java.util.Date;

/**
 * @author xueyj
 * @date 9:53 2020/12/18
 */
@Service
@Slf4j
public class WxPayServiceImpl implements WxPayService {


    @Autowired
    private WxPayV3Util wxPayV3Util;

    @Override
    public CommonResult unfiedOrder(String openId, Integer produceCode)
            throws IOException, NoSuchAlgorithmException, InvalidKeyException, SignatureException {
        if (openId == null || openId.isEmpty() || produceCode == null) {
            return CommonResult.failed("缺少传入参数");
        }

        /*套餐*/
        TProduct tProduct = TProduct.builder().build();
        /*内部订单号*/
        String orderCode = "sdsadasd";

        /*
         *组装body，转换为json
         * tProduct 套餐，ordercode 订单号,openId 小程序唯一标识
         */
        String jsonStr = wxPayV3Util.mustUniFiledStr(tProduct, orderCode, openId);

        /*打开wx链接，配置请求头签名*/
        CloseableHttpClient client = wxPayV3Util.wxClient();

        /*获得下单post请求*/
        HttpPost httpPost = wxPayV3Util.getPostHttp();

        /*报文主体*/
        StringEntity entity = new StringEntity(jsonStr, StandardCharsets.UTF_8);

        httpPost.setEntity(entity);

        CloseableHttpResponse response = client.execute(httpPost);

        /*返回数据*/
        String g1 = EntityUtils.toString(response.getEntity(), StandardCharsets.UTF_8);

        client.close();

        /*请求状态code*/
        int statusCode = response.getStatusLine().getStatusCode();

        response.close();

        /*以下code为200的业务操作*/
        return null;
    }

    @Override
    public CommonResult notifyWeiXinPayV3(HttpServletRequest request)
            throws IOException, GeneralSecurityException {
        /*获取所需的头数据*/
        String timestamp = request.getHeader(WechatPay.WECHATPAY_TIMESTAMP.getMessage());
        String nonce = request.getHeader(WechatPay.WECHATPAY_NONCE.getMessage());
        String signature = request.getHeader(WechatPay.WECHATPAY_SIGNATURE.getMessage());

        /*读取报文*/
        StringBuilder sb = wxPayV3Util.readNotifyMessage(request);

        /*构造签名字符串*/
        String srcData = timestamp + "\n"
                + nonce + "\n"
                + sb + "\n";

        /*获取平台证书公钥*/
        PublicKey ptzPub = wxPayV3Util.getPtzPub();

        /*
         *判断是不是微信发送的
         * srcData 构造签名字符串 ,  signature 微信发送来的签名  ，ptzPub 平台证书公钥
         */
        if (!wxPayV3Util.verify(srcData, signature, ptzPub)) {
            log.info("微信签名验证错误:非微信发送");
            return CommonResult.failed("非wx发送");
        }

        /*解密报文中加密数据*/
        NotifyBody notifyBody = wxPayV3Util.decryptNotifyMessage(sb);

        // 以下业务操作
        return null;
    }
}
